package com.sgcc.sx.pmos.e_sx_personalcenter.activity;


import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sgcc.sx.pmos.arouter.personalcenter.PersonalCenterArouterPath;
import com.sgcc.sx.pmos.common.base.MvpBaseActivity;
import com.sgcc.sx.pmos.common.bean.BaseResponse;
import com.sgcc.sx.pmos.common.bean.EventCenter;
import com.sgcc.sx.pmos.common.http.HttpInterConst;
import com.sgcc.sx.pmos.common.http.HttpRequestUtils;
import com.sgcc.sx.pmos.common.http.MvcNetCallback;
import com.sgcc.sx.pmos.common.utils.ArguConstant;
import com.sgcc.sx.pmos.common.utils.BigDecimalUtils;
import com.sgcc.sx.pmos.common.utils.ReflectUtils;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.sx.pmos.e_sx_personalcenter.adapter.SetPowerRatioAdapter;
import com.sgcc.sx.pmos.e_sx_personalcenter.bean.CurveBean;
import com.sgcc.sx.pmos.e_sx_personalcenter.bean.KeyValueBean;
import com.sgcc.sx.pmos.e_sx_personalcenter.bean.PowerCurveBean;
import com.sgcc.sx.pmos.e_sx_personalcenter.contract.SetPowerRatioContract;
import com.sgcc.sx.pmos.e_sx_personalcenter.presenter.SetPowerRatioPresenter;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 设置电量比例
 */
@Route(path = PersonalCenterArouterPath.PERSONALCENTER_SETPOWERRATIO)
public class SetPowerRatioActivity extends MvpBaseActivity<SetPowerRatioPresenter> implements SetPowerRatioContract.View {

    private TitleBar mTitleBar;
    private TextView mTvTotal;
    private RecyclerView mRvDataList;
    private TextView mTvSubmit;
    private TextView mTvTotalTitle;
    private SetPowerRatioAdapter mSetPowerRatioAdapter;

    @Autowired
    public String ratioId;
    @Autowired
    public String from;
    @Autowired
    public boolean isEdit;

    private String time[] = {"00:00 ~ 01:00", "01:00 ~ 02:00", "02:00 ~ 03:00", "03:00 ~ 04:00", "04:00 ~ 05:00", "05:00 ~ 06:00",
            "06:00 ~ 07:00", "07:00 ~ 08:00", "08:00 ~ 09:00", "09:00 ~ 10:00", "10:00 ~ 11:00", "11:00 ~ 12:00",
            "12:00 ~ 13:00", "13:00 ~ 14:00", "14:00 ~ 15:00", "15:00 ~ 16:00", "16:00 ~ 17:00", "17:00 ~ 18:00",
            "18:00 ~ 19:00", "19:00 ~ 20:00", "20:00 ~ 21:00", "21:00 ~ 22:00", "22:00 ~ 23:00", "23:00 ~ 24:00",};


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_setpowerratio;
    }

    @Override
    protected SetPowerRatioPresenter createPresenter() {
        return new SetPowerRatioPresenter();
    }

    @Override
    protected void initViews() {
        super.initViews();
        mTitleBar = (TitleBar) findViewById(R.id.TitleBar);
        mTvTotal = (TextView) findViewById(R.id.tvTotal);
        mRvDataList = (RecyclerView) findViewById(R.id.rvDataList);
        mTvSubmit = (TextView) findViewById(R.id.tvSubmit);
        mTvTotalTitle = (TextView) findViewById(R.id.tvTotalTitle);
        mTitleBar.setTitle("1".equals(from) ? "设置电量比例" : "设置偏差比例");
        mTitleBar.setRightIcon(R.mipmap.go_main, view -> goMainActivity());
        mSetPowerRatioAdapter = new SetPowerRatioAdapter(mContext, from, mTvTotal);
        mRvDataList.setLayoutManager(new LinearLayoutManager(mContext));
        mRvDataList.setAdapter(mSetPowerRatioAdapter);

        String result = "1".equals(from) ? "各时段用电比例(和为1)" : "偏差比例";
        mTvTotalTitle.setText(result);

        if (!isEdit) {
            List<KeyValueBean> list = new ArrayList<>();
            for (int i = 0; i < time.length; i++) {
                KeyValueBean keyValueBean = new KeyValueBean();
                keyValueBean.setKey(time[i]);
                list.add(keyValueBean);
            }
            mSetPowerRatioAdapter.setList(list);
        } else {
            queryCurveInfo();
        }

        mRvDataList.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                KeyboardUtils.hideSoftInput(SetPowerRatioActivity.this);
            }
        });
        mTvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("1".equals(from)) {
                    String total = mTvTotal.getText().toString().trim();
                    if ("——".equals(total)) {
                        ToastUtils.showShort("请输入完整的信息");
                    } else {
                        BigDecimal bigDecimal = new BigDecimal(total);
                        if (BigDecimalUtils.compareTo(bigDecimal, BigDecimal.ONE) == 0) {
                            saveCurve();
                        } else {
                            ToastUtils.showShort("各时段用电比例(和为1)");
                        }
                    }
                } else {
                    List<KeyValueBean> list = mSetPowerRatioAdapter.getData();
                    for (KeyValueBean keyValueBean : list) {
                        if (TextUtils.isEmpty(keyValueBean.getValue())){
                            ToastUtils.showShort("请输入完整的信息");
                            return;
                        }
                    }
                    saveCurve();
                }
            }
        });
    }

    public void queryCurveInfo() {
        Map<String, Object> params = new HashMap<>();
        params.put("_t", System.currentTimeMillis());
        params.put("ratioId", ratioId);
        params.put("eSource", "1".equals(from) ? "3" : "4");
        HttpRequestUtils.getInstance().request(params, HttpInterConst.USER_QUERYCURVEINFO, new MvcNetCallback<PowerCurveBean>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);

            }

            @Override
            public void onResponse(PowerCurveBean response, int id) {
                super.onResponse(response, id);
                if (response != null) {
                    if ("200".equals(response.getCode())) {
                        if (!response.getData().isEmpty()) {
                            List<BigDecimal> list = getFieldValue(response.getData().get(0));
                            List<KeyValueBean> list_str = new ArrayList<>();
                            for (int i = 0; i < time.length; i++) {
                                KeyValueBean keyValueBean = new KeyValueBean();
                                keyValueBean.setKey(time[i]);
                                keyValueBean.setValue(list.get(i) == null ? "" : list.get(i).stripTrailingZeros().toPlainString());
                                list_str.add(keyValueBean);
                            }
                            mSetPowerRatioAdapter.setList(list_str);


                            BigDecimal result = BigDecimal.ZERO;
                            for (KeyValueBean keyValueBean : mSetPowerRatioAdapter.getData()) {
                                if (keyValueBean != null && !TextUtils.isEmpty(keyValueBean.getValue())) {
                                    result = BigDecimalUtils.add(result, new BigDecimal(keyValueBean.getValue()));
                                }
                            }

                            if ("1".equals(from)) {
                                mTvTotal.setText(result.stripTrailingZeros().toPlainString());
                            } else {
                                mTvTotal.setText("——");
                            }


                        }
                    }

                }
            }
        });
    }

    private static List<BigDecimal> getFieldValue(Object o) {
        try {
            List<BigDecimal> list = new ArrayList<>();
            String getter = "get" + "Ratio";
            for (int i = 1; i < 25; i++) {
                String s1 = getter + String.valueOf(i);
                Method method = o.getClass().getMethod(s1, new Class[]{});
                Object value = method.invoke(o, new Object[]{});
                if (value == null) {
                    list.add(null);
                } else {
                    list.add(new BigDecimal((String) value));
                }
            }
            return list;
        } catch (Exception e) {
            Log.e("TAG", "getFieldValue: " + e.toString());
        }
        return null;
    }

    public void saveCurve() {
        List<KeyValueBean> list = mSetPowerRatioAdapter.getData();
        CurveBean curveBean = new CurveBean();
        for (int i = 0; i < list.size(); i++) {
            ReflectUtils.invokeSet(curveBean, "ratio" + (i + 1), list.get(i).getValue());
        }
        curveBean.set_t(System.currentTimeMillis() + "");
        curveBean.setRatioId(ratioId);
        curveBean.setESource("1".equals(from) ? "3" : "4");

        String json = GsonUtils.toJson(curveBean);
        Log.e("TAG", "saveCurve:  = " + json);

        HttpRequestUtils.getInstance().publicRequest(json, HttpInterConst.USER_SAVECURVE, new MvcNetCallback<BaseResponse>(true) {
            @Override
            public void onError(Call call, Exception e, int id) {
                super.onError(call, e, id);
            }

            @Override
            public void onResponse(BaseResponse response, int id) {
                super.onResponse(response, id);
                if (response != null) {
                    if (response.isSuccess()) {
                        EventBus.getDefault().post(new EventCenter<>(ArguConstant.SAVE_CURVE_BACK));
                        finish();
                    }else{
                        if(!TextUtils.isEmpty(response.getMsg())){
                            ToastUtils.showShort(response.getMsg());
                        }
                    }
                }
            }
        }, null);
    }
}
